'''
Created on 30 Nov 2012

@author: quirino.brizi
'''
from types import DictType, ListType, TupleType

def merge(d1, d2):
    """
    Merge the collections passed in as a parameters into a brand new  
    dictionary. 
    The common properties will be overwritten using the values on d2.
    @param d1: the base collection
    @param d2: the extend collection
    """
    return dict(to_list(d1) + to_list(d2))

def intersect(dictview, other):
    """
    Return the intersection of the given parameters as a new set.
    """
    return dictview & other

def to_list(data):
    """
    Convert the provided parameter to list
    @param data: the object to have to convert to list, one of dict, 
    tuple, list
    """
    if data is None or isinstance(data, ListType):
        return data
    elif isinstance(data, DictType) :
        return _list(data.items())
    elif isinstance(data, TupleType) :
        return _list(data)
    else :
        raise ValueError("Data is not one of DictType, ListType or TupleType")

def _list(data):
    """
    
    """
    tmp = []
    try :
        for k,v in data :
            if isinstance(v, (TupleType, ListType)) :
                for d in v : tmp.append((k,d))
            else :
                tmp.append((k,v))
    except ValueError :
        tmp = list(data)
    return tmp
    
